package com.chiu.study;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private FrameLayout mContent;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private ListView mCatalogList;
    private CatalogAdapter mCatalogAdapter;
    private String[] mCatalogs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initToolBar();
        init();
        bindCatalogs();
    }

    private void initToolBar() {
        mToolbar = (Toolbar) this.findViewById(R.id.main_toolbar);
        mToolbar.setTitle("Home Page");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    private void init() {
        mContent = (FrameLayout) this.findViewById(R.id.main_content);
        mDrawerLayout = (DrawerLayout) this.findViewById(R.id.main_drawerlayer);
        mCatalogList = (ListView) this.findViewById(R.id.catalogs_list);
        mCatalogs = getResources().getStringArray(R.array.catalogs);
        mCatalogAdapter = new CatalogAdapter(this, R.layout.item_catalog, mCatalogs);
    }

    private void bindCatalogs() {
        mCatalogList.setAdapter(mCatalogAdapter);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close);
        mDrawerToggle.syncState();
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    class CatalogAdapter extends ArrayAdapter<String> {

        private LayoutInflater mInflater;
        private int mResource;

        public CatalogAdapter(Context context, int resource, String[] objects) {
            super(context, resource, objects);
            mInflater = LayoutInflater.from(context);
            mResource = resource;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = null;
            if (convertView != null) {
                view = convertView;
            } else {
                view = mInflater.inflate(mResource, null);
            }

            TextView catalogTitle = (TextView) view.findViewById(R.id.catalog_title);
            catalogTitle.setText(getItem(position));
            return view;
        }
    }
}
